/**
 * 项目名称（软件名称）：忠旺机械物资管理系统(mms)
 * 研发设计单位：忠旺机械设备制造有限公司机械设计院智能控制设计科设计与研发。
 * 版权所有：忠旺机械设备制造有限公司
 * 注：本项目的一切技术专利，使用规范归解释权由忠旺机械设备制造有限公司所有。
 * 软件版本：Ver 1.0.0
 * 文件路径：com.zhongwang.mms.module.purchase.service
 * 创建时间：2020年03月16日 14时06分
 **/
package com.zhongwang.mms.module.purchase.service;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.write.metadata.style.WriteCellStyle;
import com.alibaba.excel.write.metadata.style.WriteFont;
import com.alibaba.excel.write.style.HorizontalCellStyleStrategy;
import com.zhongwang.mms.common.JsonResult;
import com.zhongwang.mms.gen.entity.*;
import com.zhongwang.mms.module.basic.dao.TCostDao;
import com.zhongwang.mms.module.basic.dao.TWarehouseInfoDao;
import com.zhongwang.mms.module.basic.service.BoardService;
import com.zhongwang.mms.module.purchase.constant.PurchaseConstant;
import com.zhongwang.mms.module.purchase.dao.*;
import com.zhongwang.mms.module.purchase.model.PInModel;
import com.zhongwang.mms.module.purchase.model.PInOrder;
import com.zhongwang.mms.module.system.log.LogService;
import com.zhongwang.mms.util.ShiroUtils;
import com.zhongwang.mms.util.StringUtils;
import lombok.extern.log4j.Log4j2;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.File;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @ClassName： PurWarInManageService
 * @Description： 入库单业务逻辑层
 * @Author： 徐一贺
 * @Date： 2020/3/16 14:06
 * @Version： V1.0
 **/
@Log4j2
@Service
public class PurWarInManageService {

    @Autowired
    private PurWarInManageDao purWarInManageDao;
    @Autowired
    private TWarehouseInfoDao tWarehouseInfoDao;
    @Autowired
    private com.zhongwang.mms.module.purchase.dao.PurPOrderDetailDao purPOrderDetailDao;
    @Autowired
    private PurPOrderDao purPOrderDao;
    @Autowired
    private PurPInventoryDao purPInventoryDao;
    @Autowired
    private LogService logService;
    @Autowired
    private PurTProjectDao purTProjectDao;
    @Autowired
    private BoardService boardService;
    @Autowired
    private TCostDao tCostDao;

    @Value("${user.upload.path}")
    private String uploadPath;
    String msg = "";

//    /**
//     * @FunctionName: uploadExcelFile
//     * @Description: 导入入库单
//     * @Author: 徐一贺
//     * @CreateDate: 2020/3/16 14:10
//     * @Phone: 18241927380
//     * @Param: uploadExcelFile 上传的文件
//     * @Return: String 返回结果
//     * @Version: 1.0.0
//     */
//    public String uploadExcelFile(MultipartFile uploadExcelFile) {
//
//        try {
//            msg = "导入成功";
//            PurchaseUtil purchaseUtil = new PurchaseUtil();
//            String orderCode = purchaseUtil.getNewOrderCode(PurchaseOrderType.PRK);
//            String odrCode = purWarInManageDao.findPOrderByOdrCode(orderCode);
//            //插入主表数据
//            POrder pOrder = new POrder();
//            pOrder.setOdrType(1);
//            pOrder.setOdrRedFlag(0);
//            pOrder.setOdrDate(new Date());
//            pOrder.setOdrTakePerson(ShiroUtils.getUser().getName());
//            pOrder.setOdrRedFlag(0);
//            pOrder.setOdrCode(orderCode);
//            int pOdrId = purPOrderDao.insert(pOrder);
//            EasyExcel.read(uploadExcelFile.getInputStream(), PInModel.class, new PurWarInManageListener(purWarInManageDao, purPOrderDetailDao, pOdrId, pinModels -> {
//                if (pinModels != null && pinModels.size() > 0) {
//                    msg = "导入失败";
//                    // 导出异常Excel
//                    exportErrorExcel(pinModels);
//                }
//            })).headRowNumber(3).sheet().doRead();
//
//        } catch (Exception e) {
//            msg = "导入失败";
//            return msg;
//        }
//        return msg;
//    }

    /**
     * @FunctionName: findLastPRKOrderCode
     * @Description: 获取入库编码数量
     * @Author: 徐一贺
     * @CreateDate: 2020/3/17 14:17
     * @Phone: 18241927380
     * @Param:
     * @Return:
     * @Version:
     */
    public String findLastPRKOrderCode() {
        if (purWarInManageDao.findPRKOrderCodeCount() == 0) {
            return "";
        }
        return purWarInManageDao.findLastPRKOrderCode();
    }

    /**
     * @FunctionName: findLastPCKOrderCode
     * @Description: 获取最后出库的编码
     * @Author: 徐一贺
     * @CreateDate: 2020/3/17 14:17
     * @Phone: 18241927380
     * @Param:
     * @Return:
     * @Version:
     */
    public String findLastPCKOrderCode() {
        return purWarInManageDao.findLastPCKOrderCode();
    }


    /**
     * 异常数据导出到Excel
     */
    private void exportErrorExcel(List<PInModel> errorList) {

        if (errorList.size() <= 0) {
            return;
        }

        User user = (User) SecurityUtils.getSubject().getPrincipal();

        // 取得错误数据
        String path = uploadPath + user.getAccount() + "/";
        File dir = new File(path);
        if (!dir.exists()) {
            dir.mkdirs();
        }

        path = path + "dailyError.xlsx";
        // 头的策略
        WriteCellStyle headWriteCellStyle = new WriteCellStyle();
        WriteFont headWriteFont = new WriteFont();
        headWriteFont.setFontHeightInPoints((short) 10);
        headWriteCellStyle.setWriteFont(headWriteFont);

        // 内容的策略
        WriteCellStyle contentWriteCellStyle = new WriteCellStyle();

        // 这个策略是 头是头的样式 内容是内容的样式 其他的策略可以自己实现
        HorizontalCellStyleStrategy horizontalCellStyleStrategy =
                new HorizontalCellStyleStrategy(headWriteCellStyle, contentWriteCellStyle);

        // 这里 需要指定写用哪个class去读，然后写到第一个sheet，名字为模板 然后文件流会自动关闭
        EasyExcel.write(path, PInModel.class).registerWriteHandler(horizontalCellStyleStrategy).sheet("模板")
                .doWrite(errorList);

    }

    /**
     * 判断文件是否存在
     *
     * @param url 文件URL
     * @return 是否存在
     */
    public boolean exist(String url) {
        int i = url.lastIndexOf("files/");
        String path = uploadPath + url.substring(i + 6);
        File file = new File(path);
        if (!file.exists()) {
            return false;
        }

        return true;
    }

    /**
     * @param orderCodeType
     * @FunctionName: getOrderCode
     * @Description: 获取最新的单据编码
     * @Author: 徐一贺
     * @CreateDate: 2020/3/23 7:55
     * @Phone: 18241927380
     * @Param: orderCodeType 单据编码类型 PRK是入库 PCK是出库
     * @Return: String 返回最新的编码
     * @Version: 1.0.0
     */
    public String getOrderCode(int orderCodeType) {
        String orderCode = "";
        if (orderCodeType == PurchaseConstant.PRK) {
            orderCode = generatePRKOrderCode();
        } else if (orderCodeType == PurchaseConstant.PCK) {
            orderCode = generatePCKOrderCode();
        }
        return orderCode;
    }

    /**
     * @FunctionName: findLastPRKOrderCode
     * @Description: 获取最新出库单编码
     * @设计思路： 1.判断年后两位+月+日与当前年月日是否相同，如果相同且流水号则在流水号上递增1。
     * 2.如果数据为空则按照以PRK+年（后两位）月日+001生成外购件出库单编码。
     * 3.如果不相同则按照以PRK+年（后两位）月日+001生成外购件出库单编码。
     * @Author: 徐一贺
     * @CreateDate: 2020/3/17 14:22
     * @Phone: 18241927380
     * @Param:
     * @Return: String 最新出库单编码
     * @Version:
     */
    private String generatePRKOrderCode() {
        String newGeneratePRKOrderCode = "";
        //获取最后编码
        String lastPRKOrderCode = findLastPRKOrderCode();
        //获取当前时间简码
        String datetimeCode = new SimpleDateFormat("yyMMdd").format(new Date());
        Integer sn = 0;
        if (lastPRKOrderCode.length() > 0) {
            //获取外购件库最新最后的入库单号
            sn = Integer.parseInt(lastPRKOrderCode.substring(9));
        }

        if (lastPRKOrderCode.length() == 0) {
            newGeneratePRKOrderCode = "PRK" + new SimpleDateFormat("yyMMdd").format(new Date()) + "001";
        } else if (!lastPRKOrderCode.substring(3, 9).equals(datetimeCode)) {
            newGeneratePRKOrderCode = "PRK" + new SimpleDateFormat("yyMMdd").format(new Date()) + "001";
        } else {
            newGeneratePRKOrderCode = "PRK" + new SimpleDateFormat("yyMMdd").format(new Date()) + String.format("%03d", (sn + 1));
        }
        return newGeneratePRKOrderCode;
    }


    /**
     * @FunctionName: findLastPRKOrderCode
     * @Description: 获取最新出库单编码
     * @设计思路： 1.判断年后两位+月+日与当前年月日是否相同，如果相同且流水号则在流水号上递增1。
     * 2.如果数据为空则按照以PRK+年（后两位）月日+001生成外购件出库单编码。
     * 3.如果不相同则按照以PRK+年（后两位）月日+001生成外购件出库单编码。
     * @Author: 徐一贺
     * @CreateDate: 2020/3/17 14:22
     * @Phone: 18241927380
     * @Param:
     * @Return: String 最新出库单编码
     * @Version:
     */
    private String generatePCKOrderCode() {
        String newGeneratePRKOrderCode = "";
        //获取最后编码
        String lastPCKOrderCode = findLastPCKOrderCode();
        //获取当前时间简码
        String datetimeCode = new SimpleDateFormat("yyMMdd").format(new Date());
        if (lastPCKOrderCode == null) {
            newGeneratePRKOrderCode = "PCK" + new SimpleDateFormat("yyMMdd").format(new Date()) + "001";
        } else if (!lastPCKOrderCode.substring(3, 9).equals(datetimeCode)) {
            newGeneratePRKOrderCode = "PCK" + new SimpleDateFormat("yyMMdd").format(new Date()) + "001";
        } else {
            //获取外购件库最新最后的入库单号
            Integer sn = Integer.parseInt(lastPCKOrderCode.substring(9));
            newGeneratePRKOrderCode = "PCK" + new SimpleDateFormat("yyMMdd").format(new Date()) + String.format("%03d", (sn + 1)); //25为int型 ;
        }
        return newGeneratePRKOrderCode;
    }

    /**
     * @FunctionName: create
     * @Description: 创建入库单
     * @Author: 徐一贺
     * @CreateDate: 2020/3/23 10:46
     * @Phone: 18241927380
     * @Param: [pInOrder] 入库数据
     * @Return: com.zhongwang.mms.common.JsonResult 返回结果
     * @Version: 1.0.0
     */
    @Transactional(rollbackFor = Exception.class)
    public String create(PInOrder pInOrder, List<TCost> tCostList, List<TWarehouseInfo> tWarehouseInfoList, String odrCode) throws ParseException {
        //创建主单数据
        POrder pOrder = new POrder();
        pOrder.setOdrCode(odrCode);
        pOrder.setOdrRemark(pInOrder.getFormData().getOdrRemark());
        pOrder.setOdrType(1);
        pOrder.setOdrRedFlag(0);
        pOrder.setOdrDate(new Date());
        pOrder.setOdrTakePerson(pInOrder.getFormData().getOdrTakePerson());
        pOrder.setOdrReqFlag(0);
        pOrder.setOdrChangeFlag(0);
        pOrder.setOdrMakeDate(new Date());
        pOrder.setOdrMakePersonId(ShiroUtils.getUser().getId());
        pOrder.setOdrDept(pInOrder.getFormData().getOdrDept());
        pOrder.setOdrOutType(pInOrder.getFormData().getOdrOutType());
        purPOrderDao.insert(pOrder);
        Integer odrId = pOrder.getOdrId();
        List<List<POrderDetail>> insertList = new ArrayList<List<POrderDetail>>();
        int insertListIndex = 0;
        //创建明细单
        for (com.zhongwang.mms.module.purchase.model.POrderDetail pOrderDetailModel : pInOrder.getInsertData()) {
            if (null != pOrderDetailModel.getOdaTrackCode() && pOrderDetailModel.getOdaTrackCode().trim().replace("\\s", "").replace("\n", "").equals("000000")) {
                pOrderDetailModel.setOdaTrackCode("");
            }
            POrderDetail pOrderDetail = new POrderDetail();
            pOrderDetail.setOdaType(1);
            pOrderDetail.setOdaOdrId(odrId);
            pOrderDetail.setOdaRedFlag(0);
            pOrderDetail.setOdaSapCode(StringUtils.replaceNbspToSpace(pOrderDetailModel.getOdaSapCode()));
            pOrderDetail.setOdaMatDesc(StringUtils.replaceNbspToSpace(pOrderDetailModel.getOdaMatDesc()));
            pOrderDetail.setOdaNum(pOrderDetailModel.getOdaNum());
            pOrderDetail.setOdaNumUnit(pOrderDetailModel.getOdaNumUnit());
            pOrderDetail.setOdaTotalPrice(pOrderDetailModel.getOdaTotalPrice());
            pOrderDetail.setOdaNumPrice(pOrderDetailModel.getOdaNumPrice());
            pOrderDetail.setOdaTrackCode(pOrderDetailModel.getOdaTrackCode());
            pOrderDetail.setOdaBrand(pOrderDetailModel.getOdaBrand());
            if (pOrderDetailModel.getOdaProName() != null) {
                pOrderDetail.setOdaProName(StringUtils.replaceNbspToSpace(pOrderDetailModel.getOdaProName()));
            }
            if (pOrderDetailModel.getOdaProCode() != null) {
                pOrderDetail.setOdaProCode(boardService.projectCodeHandle(pOrderDetailModel.getOdaProCode()));
            }
            for (TWarehouseInfo tWarehouseInfo : tWarehouseInfoList) {
                if (tWarehouseInfo.getWhiCode().equals(pOrderDetailModel.getWarehouseLocation())) {
                    pOrderDetail.setOdaWhiId(tWarehouseInfo.getWhiId());
                    break;
                }
            }
            pOrderDetail.setOdaPosition(pOrderDetailModel.getOdaPosition());
            if (pOrderDetailModel.getOdaBookkeepingDate() != null && !pOrderDetailModel.getOdaBookkeepingDate().isEmpty()) {
                pOrderDetail.setOdaBookkeepingDate(new SimpleDateFormat("yyyy-MM-dd").parse(pOrderDetailModel.getOdaBookkeepingDate().replace('/', '-')));
            }
            pOrderDetail.setOdaSpec(pOrderDetailModel.getOdaSpec());
            boolean isCostProject = false;
            for (int j = 0; j < tCostList.size(); j++) {
                if (tCostList.get(j).getCosProCode().equals(pOrderDetail.getOdaProCode())) {
                    isCostProject = true;
                    break;
                }
            }
            if (isCostProject) {
                pOrderDetail.setOdaStockType(1);
            } else if (pOrderDetailModel.getOdaItyStockType().equals("项目在库")) {
                pOrderDetail.setOdaStockType(2);
            } else if (pOrderDetailModel.getOdaItyStockType().equals("库存在库")) {
                pOrderDetail.setOdaStockType(1);
            }
            pOrderDetail.setContractNo(pOrderDetailModel.getContractNo());
            pOrderDetail.setOdaRemarkType(pOrderDetailModel.getOdaRemarkType());
            pOrderDetail.setOdaCaseNo(pOrderDetailModel.getOdaCaseNo());
            purPOrderDetailDao.insert(pOrderDetail);
            PInventory pInventory = new PInventory();
            pInventory.setItyMatCode(pOrderDetail.getOdaMatCode());
            pInventory.setItySapCode(pOrderDetail.getOdaSapCode());
            pInventory.setItyMatDesc(pOrderDetail.getOdaMatDesc());
            pInventory.setItyNum(pOrderDetail.getOdaNum());
            pInventory.setItyAvaNum(pOrderDetail.getOdaNum());
            pInventory.setItyNumUnit(pOrderDetail.getOdaNumUnit());
            pInventory.setItyPrice(pOrderDetail.getOdaNumPrice());
            pInventory.setItyTrackCode(pOrderDetail.getOdaTrackCode());
            pInventory.setItyProName(pOrderDetail.getOdaProName());
            pInventory.setItyProCode(pOrderDetail.getOdaProCode());
            pInventory.setItyWhiId(pOrderDetail.getOdaWhiId());
            pInventory.setItyPosition(pOrderDetail.getOdaPosition());
            pInventory.setItyRemark(pOrderDetail.getOdaSpec());
            pInventory.setItyBrand(pOrderDetail.getOdaBrand());
            pInventory.setItyRowNo(pOrderDetail.getOdaId());
            pInventory.setItyStockType(pOrderDetail.getOdaStockType());
            pInventory.setItyBookkeepingDate(pOrderDetail.getOdaBookkeepingDate());
            pInventory.setItyRemarkType(pOrderDetail.getOdaRemarkType());
            pInventory.setContractNo(pOrderDetail.getContractNo());
            pInventory.setItyCaseNo(pOrderDetail.getOdaCaseNo());
            purPInventoryDao.insert(pInventory);
        }
        return "单据保存成功！";
    }
}